package com.qf.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.qf.vo.R;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ASUS
 * @version V1.0
 * @Project work
 * @Package com.qf.controller
 * @Date 2021/10/9 19:34
 */
@RestController
public class UploadController {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String newName = UUID.randomUUID().toString() + suffixName;
        //保存到本地
//        file.transferTo(new File("D://pic//"+newName));
        //保存到阿里云的oss
        String s = Base64.encodeBase64String(file.getBytes());
        System.out.println(s);
        //1、构建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //2、上传文件到OSS服务器
        ossClient.putObject(bucketName,newName,file.getInputStream());
        //声明文件访问地址
        String url = "https://"+bucketName+"."+endpoint+"/"+newName;
        System.out.println("图片路径 = "+url);
        return R.ok();
    }


    @PostMapping("/uploadBase64")
    public R uploadBase64(String file,String suffix){
        byte[] bytes = Base64.decodeBase64(file);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        //1、构建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String newName = UUID.randomUUID().toString()+suffix;
        ossClient.putObject(bucketName,newName,inputStream);
        //声明文件访问地址
        String url = "https://"+bucketName+"."+endpoint+"/"+newName;
        System.out.println("图片路径 = "+url);
        return R.ok();
    }
}
